import { api } from '../api/index'

const getUser = function (callback) {
  let token = wx.getStorageSync('token');
  // eslint-disable-next-line no-invalid-this
  let that = this;

  console.log('2----getApp().globalData', token);
  if (that.employIdCallback){// 判断app.js中是否存在该回调函数，也就是是否存在改方法
    that.employIdCallback();
  }
  // let token = getApp().globalData.token;
  // console.log("getUser", getApp().globalData.token);
  // if (token) {
  //   wx.$http.post(api.userInfo, {}, true).then(res => {
  //     console.log(res)
  //     if (callback) {
  //       callback(res.data);
  //     }
  //   })
  // } else {
  //   // wx.switchTab({
  //   //   url: '/pages/home/index'
  //   // });
  // }
}
const employIdCallback = ()=>{}

const login = function () {
  console.log("login");
  return new Promise((resolve, reject) => {
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        let jscode = res.code
        wx.getUserInfo({
          success(res) {
            let params = {
              code: jscode,
              rawData: res.rawData,
              encryptedData: res.encryptedData,
              iv: res.iv,
              signature: res.signature
            }
            wx.$http.post(api.loginUrl, params, true).then(res => {
              if (res.code == 0) {
                resolve(res.data);
                wx.setStorageSync('islogin', 1)
              }
            })
          }
        })
      }
    })
  })
}


const token2User = function () {
  console.log("token2User");
  return new Promise((resolve, reject) => {
    let token = getApp().globalData.token
    console.log('token2User---b')

    console.log(token)
    if (token) {
      wx.$http
        .post(api.userInfo, {
          token
        }, true)
        .then(res => {
          if (res.code == 0) {
            resolve(res)
          } else {
            reject()
          }
        })
    } else {
      reject()
    }
  })
}

const auth = {
  login,
  token2User,
  getUser,
}
export { auth }
